package com.atguigu.guli.service.trade.service.impl;

import com.atguigu.guli.service.base.dto.CourseDto;
import com.atguigu.guli.service.base.dto.UserDto;

import com.atguigu.guli.service.base.feign.EduFeignClient;
import com.atguigu.guli.service.base.feign.UcenterFeignClient;
import com.atguigu.guli.service.base.handler.GuliException;
import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.base.utils.JwtHelper;
import com.atguigu.guli.service.trade.entity.Order;

import com.atguigu.guli.service.trade.mapper.OrderMapper;
import com.atguigu.guli.service.trade.service.OrderService;
import com.atguigu.guli.service.trade.util.OrderNoUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-12-13
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    EduFeignClient eduFeignClient;
    @Autowired
    UcenterFeignClient ucenterFiegnClient;
    @Override
    public String createOrder(HttpServletRequest request, String courseId) {
        //判断用户是否购买过课程
        //如果已购买，抛出异常(存在已支付的订单)
        String memberId = JwtHelper.getId(request);
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getCourseId , courseId);
        queryWrapper.eq(Order::getMemberId , memberId);
        Order order = baseMapper.selectOne(queryWrapper);
        if(order!=null && order.getStatus() == 1){//已购买并支付
            throw new GuliException(ResultCodeEnum.ORDER_EXIST_ERROR);
        }
        //查询订单需要的课程和用户数据
        R userDtoR = ucenterFiegnClient.getUserDto(memberId);
        if(userDtoR==null || !userDtoR.getSuccess()){
            throw new GuliException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
        }
        R courseDtoR = eduFeignClient.getCourseDto(courseId);
        if(courseDtoR==null || !courseDtoR.getSuccess()){
            throw new GuliException(ResultCodeEnum.PAY_UNIFIEDORDER_ERROR);
        }
        //feign远程访问成功接收到的数据会根据指定的类型进行转换，如果一个json字符串没有指定具体类型，默认会转为
        // LinkedHashMap
        Object obj = userDtoR.getData().get("item");
        // map=>json字符串=>UserDto
        ObjectMapper mapper = new ObjectMapper(); // 可以将对象转为json再转为指定类型的对象
        UserDto userDto = mapper.convertValue(obj, UserDto.class);

        obj = courseDtoR.getData().get("item");
        CourseDto courseDto = mapper.convertValue(obj, CourseDto.class);
        //如果存在未支付的订单(更新订单的信息 返回id)
        if(order==null){
            order = new Order();
        }
        order.setTeacherName(courseDto.getTeacherName());
        long price = courseDto.getPrice().multiply(new BigDecimal("" + 100)).longValue();
        order.setTotalFee(price);// 以后金额设计表时优先使用分作为单位
        order.setCourseCover(courseDto.getCover());
        order.setCourseTitle(courseDto.getTitle());
        order.setMobile(userDto.getMobile());
        order.setNickname(userDto.getNickname());
        order.setCourseId(courseId);
        order.setMemberId(memberId);
        if(!StringUtils.isEmpty(order.getId())){//更新订单的信息为最新的数据
            //数据需要远程访问查询
            baseMapper.updateById(order);
        }else{
            //如果没有订单，创建订单返回id
            order.setOrderNo(OrderNoUtils.getOrderNo());
            order.setStatus(0);
            baseMapper.insert(order);
        }
        return order.getId();
    }
}
